package com.lagou.homework1_4.test04;

import com.lagou.net.UserMessage;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class ServerTest {

    public static void main(String[] args) {

        ServerSocket ss = null;
        Socket s = null;
        ObjectInputStream ois = null;
        ObjectOutputStream oos = null;

        try {

            //创建ServerSocket类型的对象并指定端口号
            ss = new ServerSocket(8888);
            System.out.println("等待客户端连接请求");

            //调用accept方法, 等待客户端连接请求
            s = ss.accept();
            System.out.println("客户端连接成功");

            //使用输入输出流进行通信
            //使用对象流
            ois = new ObjectInputStream(s.getInputStream());
            Object object = ois.readObject();

            if (object instanceof UserMessage) {

                UserMessage userMessage = (UserMessage)object;
                String username = userMessage.getUser().getUsername();
                String password = userMessage.getUser().getPassword();

                if ("admin".equalsIgnoreCase(username) && "123456".equals(password)) {
                    userMessage.setType("success");
                } else {
                    userMessage.setType("failed");
                }

                oos = new ObjectOutputStream(s.getOutputStream());
                oos.writeObject(userMessage);
            }

        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            //关闭socket并释放资源
            try {
                if (null != oos) {
                    oos.close();
                }
                if (null != ois) {
                    ois.close();
                }
                if (null != s) {
                    s.close();
                }
                if (null != ss) {
                    ss.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
